﻿using Microsoft.AspNetCore.Mvc;
using NanjingbeiRailwayStation.Core;
using NanjingbeiRailwayStation.Data.ClickHouse.Entities;
using NanjingbeiRailwayStation.Data.ClickHouse.Models;
using NanjingbeiRailwayStation.Data.ClickHouse.Services;
using NanjingbeiRailwayStation.WebApi.Aggregations;

namespace NanjingbeiRailwayStation.WebApi.Controllers
{
    /// <summary>
    /// 设备管理
    /// </summary>
    /// 

    [ApiController]
    [Route("[controller]")]
    public class DeviceController : ControllerBase
    {

         
        /// <summary>
        /// 获取设备数量
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpGet("GetTotalCount")]
        public async Task<ResultRespose<int>> GetTotalCount()
        {
            var entity =await new DeviceEntityService().GetTotalCount();

            return ResultRespose<int>.BadWithData(entity);

        }



        /// <summary>
        /// 获取塔吊类设备数量
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpGet("GetTowerCraneTotalCount")]
        public async Task<ResultRespose<ulong>> GetTowerCraneTotalCount()
        {
            var entity = await new DeviceEntityService().GetTowerCraneTotalCount();

            return ResultRespose<ulong>.BadWithData(entity);

        }
        /// <summary>
        /// 获取今日有报警的塔吊设备数量
        /// </summary>
        /// <returns></returns>

        [HttpGet("GetTodayCountOfTowerCraneEquipmentWithalarms")]
        public async Task<ResultRespose<ulong>> GetTodayCountOfTowerCraneEquipmentWithalarms()
        {
            var entity = await new Data.ClickHouse.Services.DeviceEntityService().GetTodayCountOfTowerCraneEquipmentWithAlarms();

            return ResultRespose<ulong>.BadWithData(entity);

        }
        /// <summary>
        /// 获取今日正常的的塔吊设备数量
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetTodayCountOfTowerCraneEquipmentWithNormal")]
        public async Task<ResultRespose<ulong>> GetTodayCountOfTowerCraneEquipmentWithNormal()
        {
            var entity = await new Data.ClickHouse.Services.DeviceEntityService().GetTodayCountOfTowerCraneEquipmentWithNormal();

            return ResultRespose<ulong>.BadWithData(entity);

        }


        /// <summary>
        /// 获取今日离线的的塔吊设备数量
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetTodayCountOfTowerCraneEquipmentWithOffline")]
        public async Task<ResultRespose<ulong>> GetTodayCountOfTowerCraneEquipmentWithOffline()
        {

            var craneTotalCount = await new Data.ClickHouse.Services.DeviceEntityService().GetTowerCraneTotalCount();


            var normalCount = await new Data.ClickHouse.Services.DeviceEntityService().GetTodayCountOfTowerCraneEquipmentWithNormal();

            //
            var alarmsCount = await new Data.ClickHouse.Services.DeviceEntityService().GetTodayCountOfTowerCraneEquipmentWithAlarms();


            ///
            return ResultRespose<ulong>.BadWithData(craneTotalCount-normalCount-alarmsCount);

        }

        /// <summary>
        /// 获取 塔吊设备数量（正常、离线、报警）
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpGet("GetTodayMergedCountOfTowerCraneEquipment")]

        public async Task<ResultRespose<TodayMergedCountOfTowerCraneEquipment>> GetTodayMergedCountOfTowerCraneEquipment()
        {

            var craneTotalCount = await new Data.ClickHouse.Services.DeviceEntityService().GetTowerCraneTotalCount();


            var normalCount = await new Data.ClickHouse.Services.DeviceEntityService().GetTodayCountOfTowerCraneEquipmentWithNormal();

            //
            var alarmsCount = await new Data.ClickHouse.Services.DeviceEntityService().GetTodayCountOfTowerCraneEquipmentWithAlarms();

            var entity = new TodayMergedCountOfTowerCraneEquipment()
            {
                TotalCount = craneTotalCount,
                AlarmsCount = alarmsCount,
                NormalCount = normalCount,
                OfflineCount = craneTotalCount - normalCount - alarmsCount

            };

            ///
            return ResultRespose<TodayMergedCountOfTowerCraneEquipment>.BadWithData(entity);

        }
         
        /// <summary>
        /// 获取塔吊类设备数量（正常）
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetTowerCraneNormalCount")]
        public async Task<ResultRespose<ulong>> GetTowerCraneNormalCount()
        {
            var entity = await new Data.ClickHouse.Services.DeviceEntityService().GetTowerCraneTotalCount();

            return ResultRespose<ulong>.BadWithData(entity);

        }

        /// <summary>
        /// 新增设备
        /// </summary>
        /// <param name="addDeviceRequest"></param>
        /// <returns></returns>

        /*
        [HttpPost("Add")]
        public async Task<ResultRespose<int>> Add([FromBody] AddDeviceRequest  addDeviceRequest)
        {

            if(string.IsNullOrWhiteSpace( addDeviceRequest.imei))
            {
                return ResultRespose<int>.BadWithData(0, "imei is null");
            }

            var configuration = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<DeviceEntity, AddDeviceRequest>();
                cfg.CreateMap<AddDeviceRequest, DeviceEntity>();
            });
           
            var mapper = configuration.CreateMapper();
             

            var deviceEntity = mapper.Map<DeviceEntity>(addDeviceRequest);

            using var ctx = new NanjingbeiRailwayStation.Data.Postgre.Db();

           var cnt= await ctx.DeviceEntities
                .CountAsync(item => item.imei==addDeviceRequest.imei);

            if (cnt > 0)
            {
                return ResultRespose<int>.BadWithData(0, "imei is exist");
            }
 

            ctx.DeviceEntities.Add(deviceEntity);

            await  ctx.SaveChangesAsync();

            new NanjingbeiRailwayStation.Data.Redis.Services.RealTimeService().Cache(deviceEntity.imei);

            return ResultRespose<int>.OKWithData(deviceEntity.Id);
             
        }
        
         */

        /*
        /// <summary>
        /// 更新设备
        /// </summary>
        /// <param name="editDeviceRequest"></param>
        /// <returns></returns>
        [HttpPost("Edit")]
        public async Task<ResultRespose<int>> Edit([FromBody] EditDeviceRequest  editDeviceRequest)
        {
         
             
         using var ctx = new NanjingbeiRailwayStation.Data.Postgre.Db();

          var deviceEntity= await ctx.DeviceEntities
                .FirstOrDefaultAsync(item => item.Id == editDeviceRequest.Id);

            if (deviceEntity == null)
            {
                return ResultRespose<int>.BadWithData(editDeviceRequest.Id);
            }

            var configuration = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<DeviceEntity, EditDeviceRequest>();
                cfg.CreateMap<EditDeviceRequest, DeviceEntity>();
            });

            var mapper = configuration.CreateMapper();

            var newDeviceEntity = mapper.Map<DeviceEntity>(editDeviceRequest);
            newDeviceEntity.Id = deviceEntity.Id;

            ctx.Attach(newDeviceEntity).State = EntityState.Modified;
           await ctx.SaveChangesAsync();

            new NanjingbeiRailwayStation.Data.Redis.Services.RealTimeService().Cache(deviceEntity.imei);

            return ResultRespose<int>.OKWithData(editDeviceRequest.Id);
            
        }
        */


        /// <summary>
        /// 删除 设备
        /// </summary>
        /// <param name="deviceEntity"></param>
        /// <returns></returns>
        /// 
        /*
        [HttpPost("Delete")]
        public async Task<ResultRespose<int>> Delete([FromBody] EntityIdRequest  entityIdRequest)
        {
            using var ctx = new NanjingbeiRailwayStation.Data.Postgre.Db();

           var pictures= await ctx.DevicePictureEntities
                .Where(item => item.DeviceId == entityIdRequest.Id)
                .ToListAsync();

            foreach (var picture in pictures)
            {
                ctx.Attach(picture).State = EntityState.Deleted;
            }
            await ctx.SaveChangesAsync();
  

            ctx.Attach(new DeviceEntity() { Id=entityIdRequest.Id}).State = EntityState.Deleted;

             await  ctx.SaveChangesAsync();

            return ResultRespose<int>.OKWithData(entityIdRequest.Id);

        }
        */


        /// <summary>
        /// 设备列表 没有分页
        /// </summary>
        /// <param name="listDeviceRequest"></param>
        /// <returns></returns>
        /// 
        [HttpGet("List")]
        [HttpPost("List")]
        public async Task<ResultRespose<List<DeviceEntity>>> List()
        {

            var entities =await new NanjingbeiRailwayStation.Data.ClickHouse.Services.DeviceEntityService().List("");

            return ResultRespose<List<DeviceEntity>>.OKWithData(entities);


        }

      


    }
}
